package com.mhz.cae.events;

import java.util.LinkedList;
import java.util.List;

import org.anddev.andengine.engine.handler.IUpdateHandler;

/** Manages events and engines interactions */
public class EventManager implements IUpdateHandler {

	private static EventManager INSTANCE;

	/** Events queue */
	private static List<Event> mEventsQueue = new LinkedList<Event>();
	/** Listener list */
	private static List<Listener> mListeners = new LinkedList<Listener>();

	private EventManager() {
	}

	public static synchronized EventManager getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new EventManager();
		}
		return INSTANCE;
	}

	/** Push a new Event in the Event Manager */
	public void pushEvent(final Event event) {
		mEventsQueue.add(event);
	}

	/** Register a listener in the Event Manager */
	public void registerListener(final Listener listener) {
		mListeners.add(listener);
	}

	/** Process each event in the queue for each engines then remove the event */
	private void processEvent() {

		while (!mEventsQueue.isEmpty()) {
			Event event = mEventsQueue.get(0);
			if (event != null) {
				for (Listener listener : mListeners) {
					if (!listener.isDestroyed()) {
						listener.processEvent(mEventsQueue.get(0));
					} else {
						// mListeners.remove(object)
					}
				}
			}
			mEventsQueue.remove(0);
		}
	}

	@Override
	public void onUpdate(float pSecondsElapsed) {
		processEvent();
	}

	@Override
	public void reset() {
		mEventsQueue.clear();
		mListeners.clear();
	}
}
